import service from "@service";

const moduleNameMap = {
    sr: {
        serviceHandle: ({ key, provCode }) => {
            return service("srCfgCodeSelect", {
                data: {
                    codeTypeCd: key,
                    provCode,
                },
                noMessageTip: true,
            }).then((data) => {
                data.data = (data.data||[]).sort((a, b) => {
                    return a.argeSeqno - b.argeSeqno;
                })
                return _.get(data, "data", []).map((v) => ({
                    value: v.bizCode,
                    label: v.codeNm,
                    rmk: v.rmk,
                }));
            });
        },
    },
    // 外呼
    out: {
        serviceHandle: ({ key }) => {
            return service("aioutbound_queryEnum", {
                data: {
                    bussType: key,
                },
                noMessageTip: true,
            }).then((arr) => {
                if (!Array.isArray(arr)) return [];
                return arr.map(v => ({ value: v.value, label: v.text }))
            });
        },
    },
    zsk: {
        serviceHandle: ({ key,...config }) => {
            return service("staticdatabytypeid", {
                params: {
                    typeId: key,
                },
                noMessageTip: true,
                ...config
            }).then((data) => {
                return _.get(data, "DATA", []).map((v) => ({
                    value: v.DATAVALUE,
                    label: v.DATANAME,
                }));
            });
        },
    },
    cmg: {
        serviceHandle: ({ key }) => {
            return service("cmg_getParamValues", {
                    data: {
                        code: key,
                    },
                    noMessageTip: true,
            }).then((data) => {
                // 根据value去重一下
                    const list = _.get(data, "list", []).reduce((pre, now) => {
                        if(pre.some(v => v.value === now.value)) {
                            return pre;
                        }else {
                            pre.push({
                                ...now,
                                value: now.value,
                                label: now.displayValue
                            })
                            return pre;
                        }
                    }, [])
                    return list;
                    // return _.get(data, "list", []).map((v) => ({
                    //         value: v.value,
                    //         label: v.displayValue,
                    // }));
            });
        },
		},
    json: {
        serviceHandle: ({ key }) => {
                return service(key, {noMessageTip: true}).then((data) => {
                        return (data || []).map((v) => ({
                            value: v.codeValue || v.paramsCode,
                            label: v.codeName || v.paramsName,
                    }));
                });
        },
    },
    aiqm: {
        serviceHandle: ({ key }) => {
            const params = {
                start: 0,
                pageNum: 0,
                params: {
                    tenantId: "10010000",
                    paramsTypeId:key
                },
            }
            return service('aiqm_selectByParams', {noMessageTip: true, params}).then((data) => {
                return _.get(data, "list", []).map((v) => ({
                    value: v.paramsCode,
                    label: v.paramsName,
                }));
            });
        },
	},
    sam: {
        serviceHandle: ({ key }) => {
            const params = {
                code: key,
            }
            return service('getParamValues', {noMessageTip: true, data:params}).then((data) => {
                return data?.beans?.map((item) => ({
                    key: item.value,
                    value: item.value,
                    label: item.displayValue,
                }));
            });
        },
	},
    nt: {
        serviceHandle: ({ key }) => {
            const params = {
                codeTypeCd: key,
            }
            return service('nt_cfgCodeSelect', {noMessageTip: true, data:params}).then((data) => {
                return (data?.data||[]).map((item) => ({
                    key: item.bizCode,
                    value: item.bizCode,
                    label: item.codeNm,
                }));
            });
        },
	},
};

const getComputedKey = ({ key, moduleName, provCode, computedKey }) => {
    if (computedKey) {
        return computedKey;
    }
    return `${moduleName}_${key}_${provCode}`;
};

export default {
    namespaced: true,
    state: {
        dictMap: {},
        dictMapKeyMap: {},
        loadingDictMap: {},
    },
    mutations: {
        SET_DICT(state, payload) {
            let keyMap = {};

            let computedKey = getComputedKey(payload);

            state.dictMap[computedKey] = payload.data;

            payload.data.forEach((item) => (keyMap[item.value] = item));

            state.dictMapKeyMap[computedKey] = keyMap;
        },
        ADD_DICT_LOADING(state, payload) {
            let computedKey = getComputedKey(payload);

            if (!state.loadingDictMap[computedKey]) {
                state.loadingDictMap[computedKey] = [payload];
            } else {
                state.loadingDictMap[computedKey].push(payload);
            }
        },
        SET_DICT_LOADING_EMPTY(state, payload) {
            let computedKey = getComputedKey(payload);

            state.loadingDictMap[computedKey] = [];
        },
        CLEAR_DICT_LOADING(state, payload) {
            let computedKey = getComputedKey(payload);

            state.loadingDictMap[computedKey] = null;
        },
    },
    actions: {
        async getDictMap({ state, dispatch, rootState }, params) {
            const { dictMapKeyMap } = state;
            const provCode = rootState.global.provCode;

            let key = null;
            let moduleName = null;

            if (!params) {
                return;
            }

            if (typeof params === "string") {
                key = params;
                moduleName = "sr";
            } else {
                key = params.key;
                moduleName = params.moduleName;
            }

            let computedKey = getComputedKey({
                provCode,
                key,
                moduleName,
            });

            await dispatch("getDict", params);

            return dictMapKeyMap[computedKey];
        },
        async getDict({ state, commit, rootState }, params) {
            const { dictMap } = state;
            const provCode = rootState.global.provCode;

            let key = null;

            let moduleName = null;

            let noCache = false;
            let callback = null;

            let dataFormatHandle = null;


            if (!params) {
                return;
            }

            if (typeof params === "string") {
                key = params;
                moduleName = "sr";
            } else {
                key = params.key;
                moduleName = params.moduleName;
                noCache = params.noCache;
                callback = params.callback;
                dataFormatHandle = params?.dataFormatHandle
            }

            let useCallback = (data) => {
                typeof callback === 'function' && callback(data)
            }
            

            let computedKey = getComputedKey({
                provCode,
                key,
                moduleName,
            });

            if (!noCache && dictMap[computedKey]) {
                useCallback(dictMap[computedKey])
                return dictMap[computedKey];
            }

            if (state.loadingDictMap[computedKey]) {
                return new Promise((resolve, reject) => {
                    commit("ADD_DICT_LOADING", {
                        computedKey,
                        resolve: (data) => {
                            resolve(data);
                        },
                        reject: (err) => {
                            reject(err);
                        },
                    });
                });
            } else {
                commit("SET_DICT_LOADING_EMPTY", { computedKey });
            }

            let data = await moduleNameMap[moduleName]
                .serviceHandle({
                    key,
                    provCode,
                })
                .catch((err) => {
                    if (state.loadingDictMap[computedKey]) {
                        state.loadingDictMap[computedKey].forEach(
                            ({ reject }) => {
                                reject(err);
                            }
                        );

                        commit("CLEAR_DICT_LOADING", { computedKey });
                    }

                    throw err;
                });

            data.forEach((v) => {
                v.value = String(v.value);
            });
            if(dataFormatHandle) {
                data = dataFormatHandle(data)
            }
            useCallback(data)

            commit("SET_DICT", {
                key,
                moduleName,
                provCode,
                computedKey,
                data,
            });

            if (state.loadingDictMap[computedKey]) {
                state.loadingDictMap[computedKey].forEach(({ resolve }) => {
                    resolve(data);
                });

                commit("CLEAR_DICT_LOADING", { computedKey });
            }

            return data;
        },
    },
    getters: {},
};
